package com.Base.NetBase.Socket
{
	import flash.events.*;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import com.Base.Logger.Logger;
	
	public class SocketManager
	{
		//单件
		public static function get instance():SocketManager
		{
			if (! _instance)
			{
				_instance = new SocketManager(new SingletonEnforcer());
			}
			
			return _instance;
		}
		
		//构造函数
		public function SocketManager(enforcer:SingletonEnforcer):void
		{
			initialize();
		}
		
		//设置连接成功时的回调函数
		public function set onConnected(callback:Function):void
		{
			_onConnected = callback;
		}
		
		//设置获取消息时的回调函数
		public function set onReceiveMsg(callback:Function):void
		{
			_onReceiveMsg = callback;
		}
		
		//设置服务器地址
		public function set host(hostAddress:String):void
		{
			_host = hostAddress;
		}
		
		//设置端口
		public function set port(port:int):void
		{
			_port = port;
		}
		
		//连接服务器
		public function connect():void
		{
			_socket.connect(_host, _port);
		}
		
		//发送消息
		public function sendMsg(msg:Array):void
		{
			var bytes:ByteArray = MessagePackage.pack(msg);
			
			_socket.writeBytes(bytes, 0, bytes.length);			
			_socket.flush();
		}
		
		//初始化
		private function initialize():void
		{
			_host = "127.0.0.1";
			_port = 5000;
			_readHead = true;
			_msgLen = 0;
			
			_socket = new Socket();
			_socket.addEventListener(Event.CONNECT, onConnected);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onFailed);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, onDataReceived);
		}
		
		//连接成功
		private function onConnected(e:Event):void
		{
			if (null == _onConnected)
			{
				Logger.throwError("SocketManager::onConnected()-->Null callback!");
				return;
			}
			
			_onConnected();
		}
		
		//连接失败
		private function onFailed(e:IOErrorEvent):void
		{
			Logger.throwError("Socket::onFailed()-->Connect failed!");
		}
		
		//接收数据
		private function onDataReceived(e:ProgressEvent):void
		{			
			if (null == _receiveData)
			{
				Logger.throwError("Socket::onDataReceived()-->Callback hasn't been set!");
				return;
			}
			
			parseData();
		}
		
		//解析接收到的数据
		private function parseData():void
		{			
			//需要读取信息头
			if (_readHead)
			{
				//信息长度够长时读取信息头
				if (_socket.bytesAvailable >= MSG_HEAD_LENGTH)
				{
					_msgLen = _socket.readUnsignedInt();
					_readHead = false;
				}
			}
			//不需要读取信息头
			else
			{
				//消息长度为0时一般是服务器出错或即将断开连接
				if (0 == _msgLen)
				{
					Logger.throwError("Socket::parseData()-->Message length is 0!");
					return;
				}
				
				//数据足够长时读取消息内容并回传
				if (_socket.bytesAvailable >= _msgLen)
				{
					var bytes:ByteArray = new ByteArray();
					var msg:MessagePackage = new MessagePackage();
					
					_socket.readBytes(bytes, 0, _msgLen);
					msg.data = bytes;					
					_onReceiveMsg(msg);
					_readHead = true;
				}
			}
			
			//如果剩余数据满足读取条件，继续读取数据
			if (_socket.bytesAvailable >= MSG_HEAD_LENGTH)
			{
				parseData();
			}
		}
		
		private static var _instance:SocketManager;
		
		private const MSG_HEAD_LENGTH:int = 4;
		
		private var _onConnected	:Function;
		private var _onReceiveMsg	:Function;
		private var _socket			:Socket;
		private var _host			:String;
		private var _port			:int;
		private var _readHead		:Boolean;
		private var _msgLen			:int;
	}
}

class SingletonEnforcer
{
	
}